package com.topic.simple;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.DeliverCallback;

/**
 * topic类型交换机是最强大的交换机，支持通配符，有2个
 *    *：代表一个单词
 *    #：代表0或多个单词
 *    比如一个队列q1的绑定key是*.orange.*,队列q2的绑定是*.*.rabbit和lazy.#
 *    那么，如果发送消息时的路由key发送消息情况如下：
 *    1.quick.orange.rabbit：会发给2个队列
 *    2.lazy.orange.elephant：会发给2个队列
 *    3.quick.orange.fox：会发给第一个队列
 *    4.lazy.brown.fox：只发给第二个队列
 *    5.lazy.pink.rabbit：只发给第二个队列一次，虽然2个绑定都匹配，但不会把消息发到此队列2次
 *    6.quick.brown.fox：消息会被丢弃
 *    7.orange或者uick.orange.male.rabbit，消息会被丢弃
 *    8.lazy.orange.male.rabbit：会被发给第二个队列
 *
 *    topic类型交换机模拟其它类型交换机
 *    1. 绑定key是#类似于fanout交换机
 *    2. 绑定key中没有通配符类似于direct交换机
 */
public class ReceiveLogsTopicSimple {

    public static final String EXCHANGE_NAME = "cj_topic_simple";


    public static void main(String[] argv) throws Exception {
        ConnectionFactory factory = new ConnectionFactory();
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();

        channel.exchangeDeclare(EXCHANGE_NAME, "topic");
        String queueName = channel.queueDeclare().getQueue();

        channel.queueBind(queueName, EXCHANGE_NAME, "*.orange.*");

        System.out.println(" [*.orange.*] Waiting for messages. To exit press CTRL+C");

        DeliverCallback deliverCallback = (consumerTag, delivery) -> {
            String message = new String(delivery.getBody(), "UTF-8");
            System.out.println(" [*.orange.*] Received '" + delivery.getEnvelope().getRoutingKey() + "':'" + message + "'");
        };
        channel.basicConsume(queueName, true, deliverCallback, consumerTag -> { });
    }
}